package cn.stylefeng.guns.modular.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.modular.entity.Frame;
import cn.stylefeng.guns.modular.entity.Frameitem;
import cn.stylefeng.guns.modular.entity.Schedule;
import cn.stylefeng.guns.modular.model.FrameAnditemDto;
import cn.stylefeng.guns.modular.service.FrameService;
import cn.stylefeng.guns.modular.service.FrameitemService;
import cn.stylefeng.guns.modular.service.ScheduleIndexService;
import cn.stylefeng.guns.modular.warpper.FrameWrapper;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 *
 * 日程框架控制器
 *
 * @author third_e
 * @create 2019/12/10 0010-下午 3:48
 */
@Controller
@RequestMapping("/frame")
public class FrameController extends BaseController {

    private static String PREFIX = "/frame";

    @Autowired
    public FrameService frameService;

    @Autowired
    public FrameitemService frameitemService;

    @Autowired
    public ScheduleIndexService scheduleIndexService;


    /**
     * 跳转到日程框界面
     */

    @RequestMapping("")
    public String index(){
        return PREFIX +"/frame.html";
    }

    /**
     * 跳转到创建日程框架界面
     * @return
     */
    @RequestMapping("/create")
    public String frameCreate(){
        return PREFIX +"/frame_create.html";
    }


    /**
     * 跳转到编辑页面
     *
     * @param frameId
     * @return
     */
    @RequestMapping("/edit")
    public String frameEdit(@RequestParam Long frameId){
//        //获取当前登录的用户
//        LoginUser user =  LoginContextHolder.getContext().getUser();
//        model.addAttribute("user",JSON.toJSON(user));
//        System.out.println("\n\naaaaaaaaaa"+model.toString());
        //判断请求是否错误

        if (ToolUtil.isEmpty(frameId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Frame frame = this.frameService.getById(frameId);

        if (frame.getPostStatus().equals("ENABLE")){
            return PREFIX + "/frame_edit_release.html";
        }else {
            //跳转到编辑界面
            return PREFIX + "/frame_edit.html";
        }


    }

    /**
     * 跳转到查看框架界面
     */
    @RequestMapping("/view")
    public String frameView(@RequestParam Long frameId){
        return PREFIX + "/frame_view.html";
    }

    /**
     * 创建保存
     * 添加日程框架和日程框架项
     *
     * @param frameAnditemDto
     * @return
     */
    @RequestMapping(value = "/frame_add")
    @ResponseBody
//    public ResponseData add(Frame frame, Frameitem frameitem){
    public ResponseData add(FrameAnditemDto frameAnditemDto){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        //获取日程框架
        Frame frame = new Frame();
        frame.setUserId(user.getId());
        frame.setFrameName(frameAnditemDto.getFrameName());
        frame.setFrameDescription(frameAnditemDto.getFrameDescription());
        frame.setStatus(frameAnditemDto.getStatus());
        //判断日程框架是否重复
        Frame theFrame = this.frameService.getByName(frame.getFrameName());
        if(theFrame !=null){
            throw new ServiceException(BizExceptionEnum.FRAME_DUPLIOATE_NAME);
        }
        //创建日程框架
        this.frameService.addFrame(frame);
        //创建日程框架项
        this.frameitemService.addFrameitem(frameAnditemDto);

        return SUCCESS_TIP;
    }


    /**
     * 创建保存并发布
     * 添加日程框架和日程框架项
     *
     * @param frameAnditemDto
     * @return
     */
    @RequestMapping(value = "/frame_addAndRelese")
    @ResponseBody
    public ResponseData addAndRelese(FrameAnditemDto frameAnditemDto){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();

        //判断是否是草稿框架，通过id判断是否为null
        if (ToolUtil.isEmpty(frameAnditemDto.getFrameId())){
            //获取日程框架
            Frame frame = new Frame();
            frame.setUserId(user.getId());
            frame.setFrameName(frameAnditemDto.getFrameName());
            frame.setFrameDescription(frameAnditemDto.getFrameDescription());
            frame.setStatus(frameAnditemDto.getStatus());
            //判断日程框架是否重复

            Frame theFrame = this.frameService.getByName(frame.getFrameName());
            if(theFrame !=null){
                throw new ServiceException(BizExceptionEnum.FRAME_DUPLIOATE_NAME);
            }
            //创建日程框架
            this.frameService.addFrame(frame);
            //创建日程框架项
            this.frameitemService.addFrameitem(frameAnditemDto);
            //发布日程框架
            this.frameService.release(frame.getFrameId()); //发布该框架

        }else {
            //已存在草稿，查询id
            Frame isDraftFrame = this.frameService.getById(frameAnditemDto.getFrameId());
            if (isDraftFrame.getFrameId().equals(frameAnditemDto.getFrameId())){//相同则补充内容,更新,不相同则存储
                isDraftFrame.setFrameName(frameAnditemDto.getFrameName());
                isDraftFrame.setFrameDescription(frameAnditemDto.getFrameDescription());
                isDraftFrame.setStatus(frameAnditemDto.getStatus());
                isDraftFrame.setUserId(user.getId());
                isDraftFrame.setPostStatus("ENABLE");
                this.frameService.updateById(isDraftFrame);
                //创建日程框架项
                this.frameitemService.addFrameitem(frameAnditemDto);
            }
        }
        return SUCCESS_TIP;
    }


    /**
     * 获取当前用户全部日程框架
     * @param nameOrcontent
     * @param otherOrmyself
     * @param timeLimit
     * @return
     */
    @RequestMapping(value = "/frame_list")
    @ResponseBody
    public Object list(@RequestParam(value = "nameOrcontent", required = false) String nameOrcontent,
                       @RequestParam(value = "otherOrmyself", required = false) String otherOrmyself,
                       @RequestParam(value = "timeLimit", required = false) String timeLimit){

        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();

        //直接查询
//        Collection<Frame> frames = this.frameService.selectFrames(frameName,user.getId());

        //分页显示
        Page<Map<String, Object>> frames = this.frameService.selectFrames(nameOrcontent,otherOrmyself,beginTime,endTime,user.getId());
        Page<Map<String, Object>> wrap = new FrameWrapper(frames).wrap();

//        return frames;
        return LayuiPageFactory.createPageInfo(wrap) ;
    }


    /**
     * 获取当前用户某个框架信息
     * @param frameId
     * @return
     */
    @RequestMapping(value = "/getOneFrameInfo")
    @ResponseBody
    public ResponseData OneFrameAllInfo(@RequestParam Long frameId){
        //判断请求id是否有误
        if (ToolUtil.isEmpty(frameId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }

        Frame frame = this.frameService.getAllFrameInfo(frameId);
//        Collection<Frameitem> frameitem = this.frameitemService.getFrameId(frameId);
//        Map<String, Object> frameMap = BeanUtil.beanToMap(frame);

        return ResponseData.success(frame);
    }


    /**
     * 编辑保存
     */
    @RequestMapping(value = "/frame_editadd")
    public ResponseData editAdd(FrameAnditemDto frameAnditemDto){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        //获取当前框架信息
        Frame theframe = this.frameService.getById(frameAnditemDto.getFrameId());
        //判断当前用户是否有权限修改当前框架
        if(!user.getId().equals(theframe.getUserId())){
            throw new ServiceException(BizExceptionEnum.NO_PERMITION);
        }
        //获取日程框架
        Frame frame = new Frame();
        frame.setFrameId(frameAnditemDto.getFrameId());
        frame.setFrameName(frameAnditemDto.getFrameName());
        frame.setFrameDescription(frameAnditemDto.getFrameDescription());
        frame.setStatus(frameAnditemDto.getStatus());
        //保存编辑日程框架
        this.frameService.editAdd(frame);
        //未发布的日程框架则可以保存日程框架项，
        if (theframe.getPostStatus().equals("DISABLE")) {
            this.frameitemService.editAdd(frameAnditemDto);
        }
        return SUCCESS_TIP;
    }



    /**
     * 发布日程框架
     */
    @RequestMapping("/releaseFrame")
    @ResponseBody
    public ResponseData releaseFrame(@RequestParam Long frameId){
        //判断请求是否无误
        if (ToolUtil.isEmpty(frameId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.frameService.release(frameId); //发布该框架
        return SUCCESS_TIP;
    }



    /**
     * 删除日程框架
     */
    @RequestMapping("/deleteFrame")
    @ResponseBody
    public ResponseData delete(@RequestParam Long frameId){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        //获取当前框架信息
        Frame theframe = this.frameService.getById(frameId);
        //判断当前用户是否有权限删除当前框架
        if(!user.getId().equals(theframe.getUserId())){
            throw new ServiceException(BizExceptionEnum.NO_PERMITION);
        }
        Collection<Schedule> schedules = this.scheduleIndexService.getScheduleByframeId(frameId);
        //判断框架是否被日程使用,未使用删除
        if (ToolUtil.isEmpty(schedules)){
            this.frameitemService.deleteFrameitem(frameId);
        }else { //已被使用，判断日程是否全部被删除，全部删除则删除日程项，否则不删除
            boolean allDelete = true;
            for (Schedule schedule:schedules){
                if (!schedule.getPublicStatus().equals("DELETE")){
                    allDelete = false;
                }
            }
            if (allDelete){
                this.frameitemService.deleteFrameitem(frameId);
            }
        }
        this.frameService.deleteFrame(frameId);

        return SUCCESS_TIP;
    }


    /**
     * 获取一个框架详情数据
     * @param frameId
     * @return
     */
    @RequestMapping("frame_detailed")
    @ResponseBody
    public ResponseData getFrameDetailed(@RequestParam Long frameId){
        Frame frame = this.frameService.getById(frameId);
        Collection<Frameitem> frameitem = this.frameitemService.selectFramitem(frameId);
        Map<String,Object> result = new HashMap<>();
        result.put("frame",frame);
        result.put("frameitem",frameitem);
        return ResponseData.success(result);
    }

}
